package jw.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import jw.srb.oss.service.FileService;
import jw.srb.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;


@Service
public class FIleServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

        // 判断BUCKET_NAME是否存在
        if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            // 权限为读写权限
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        // 上传文件流
        // 文件目录结构 "avatar/2021/11/04/"
        // 文件名生成(拿到拓展名的技巧)
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        // 构建日期路径
        String timeFolder = new DateTime().toString("/yyyy/MM/dd/");
        String key = module + timeFolder + fileName;
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        // 返回URL地址

        return "https://" + OssProperties.BUCKET_NAME+ "." +OssProperties.ENDPOINT+ "/" +key;
    }

    @Override
    public void removeFile(String url) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

        // 删除文件或目录。如果要删除目录，目录必须为空。
        // 文件名称
        String host = "https://" + OssProperties.BUCKET_NAME+ "." +OssProperties.ENDPOINT+ "/";
        // 又是一个小tips，截掉他前面的长度，就是objectName

        String objectName = url.substring(host.length(),url.indexOf("?"));
        ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
        System.out.println(objectName);
        // 关闭OSSClient。
        ossClient.shutdown();

    }
}
